<template>
  <div>
    <!-- 新增或者修改采购单 -->
    <el-form
      :model="addForm"
      ref="addFormRef"
      label-position="top"
      :rules="rules"
    >
      <el-form-item label="供应商名称" prop="providerId">
        <el-select
          v-model="addForm.providerId"
          placeholder="请输入供应商名称或联系方式检索"
          filterable
        >
          <el-option
            v-for="item in props.providerList"
            :key="item.id"
            :label="item.providerName + '_' + item.providerPhone"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务员名称" prop="businessUserId">
        <el-select
          v-model="addForm.businessUserId"
          placeholder="请输入业务员名称检索"
          filterable
        >
          <el-option
            v-for="item in props.employeeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="采购时间" prop="businessTime">
        <el-date-picker
          v-model="addForm.businessTime"
          type="datetime"
          placeholder="请选择采购时间"
          format="YYYY-MM-DD hh:mm:ss"
          value-format="x"
          class="w-full"
        />
      </el-form-item>
    </el-form>

    <el-divider class="mt-5 mb-3"> 采购明细 </el-divider>

    <div class="w-full flex justify-end items-center">
      <el-button type="primary" icon="Pointer" @click="openDrawer"
        >选择商品</el-button
      >
    </div>

    <el-table :data="tableData" style="height: calc(100vh - 20rem)">
      <el-table-column label="编码" align="center">
        <template #default="{ row }">
          <span>{{ row.myCode ? row.myCode : row.goodsCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品" align="center">
        <template #default="{ row }">
          <div style="margin-left: 10px; width: 160px">
            <p>{{ row.goodsTitle }}</p>
            {{ row.categoryName + row.typeName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="拼音码" align="center">
        <template #default="{ row }">
          <span>{{ row.spelling }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center">
        <template #default="{ row }">
          <span>
            {{
              row.specsDescription ? row.specsDescription : row.goodsSpecName
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="采购单价(元)" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.priceAtOrder"
            :min="0"
            :precision="2"
            :step="0.1"
            :max="99999999999999"
          />
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center">
        <template #default="{ row }">
          <el-input-number v-model="row.count" :min="0" />
        </template>
      </el-table-column>
      <el-table-column label="个性化标签" prop="description" align="center">
      </el-table-column>
      <el-table-column label=" 分项金额(元)" align="center">
        <template #default="{ row }">
          <span>
            {{ handleMul(row.priceAtOrder, row.count).toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100">
        <template #default="{ row }">
          <el-button type="danger" link @click="deleteRow(row.deleteId)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="fixed bottom-2 right-2">
      <el-button>取消</el-button>
      <el-button type="primary" @click="handleSubmit(1)" :loading="loading"
        >保存草稿</el-button
      >
      <el-button type="primary" @click="handleSubmit(2)" :loading="loading"
        >保存提交</el-button
      >
    </div>

    <el-drawer
      v-model="product_drawer"
      destroy-on-close
      title="选择商品"
      size="80%"
    >
      <ChangeProduct @handleChangeOneProduct="handleChangeProductSuccess" />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import Decimal from "decimal.js";
import ChangeProduct from "@/components/ChangeProduct.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  GetGlassesStorePurchaseOrderDetail,
  CreateGlassesStorePurchaseOrder,
  UpdateGlassesStorePurchaseOrder,
} from "../../../../../wailsjs/go/api/OrderApi";

onMounted(() => {
  if (props.detailForm.id != 0) {
    getDetail();
  } else {
    addForm.value.businessTime = new Date().getTime();
  }
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  detailForm: {
    type: Object,
    default: () => {},
  },
  providerList: {
    type: Array,
    default: () => [],
  },
  employeeList: {
    type: Array,
    default: () => [],
  },
});

const addFormRef = ref(null);
const addForm = ref({
  providerId: null,
  providerName: "",
  businessUserId: null,
  businessUserName: "",
  businessTime: null,
  customerId: null,
  discount: 0,
  paidAmount: 0,
  quantity: 0,
  status: null,
  totalAmount: 0,
  items: [],
});

const handleCancel = (val = 0) => {
  addFormRef.value.resetFields();
  emit("handleBack", val);
};

const loading = ref(false);
const handleSubmit = (type) => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    addForm.value.status = type; // 1 草稿 2 提交

    if (!tableData.value || tableData.value.length == 0) {
      return ElMessage.warning("请选择商品");
    }

    // loading.value = true;

    addForm.value.items = tableData.value;
    let form = cloneDeep(addForm.value);
    form.customerId = form.providerId;
    form.providerName =
      props.providerList.find((item) => item.id == form.providerId)
        .providerName || "";
    form.businessUserName =
      props.employeeList.find((item) => item.id == form.businessUserId).name ||
      "";
    form.businessTime = form.businessTime / 1000;

    form.quantity = form.quantity ? form.quantity : 0;
    form.paidAmount = form.paidAmount ? form.paidAmount : 0;
    form.totalAmount = form.totalAmount ? form.totalAmount : 0;
    form.items.forEach((item) => {
      form.quantity += item.count;

      item.priceAtOrder = handleMul(item.priceAtOrder, 100);

      form.paidAmount += handleMul(item.priceAtOrder, item.count);
      form.totalAmount += handleMul(item.priceAtOrder, item.count);
    });

    if (props.detailForm.id == 0) {
      handleApiResponse(() =>
        CreateGlassesStorePurchaseOrder({ glassesStorePurchaseOrder: form })
      ).then((res) => {
        if (res.code == 0) {
          if (type == 1) {
            ElMessage.success("保存成功");
          } else {
            ElMessage.success("提交成功");
          }
          handleCancel(1);
        }
        loading.value = false;
      });
    } else {
      handleApiResponse(() =>
        UpdateGlassesStorePurchaseOrder({ glassesStorePurchaseOrder: form })
      ).then((res) => {
        if (res.code == 0) {
          if (type == 1) {
            ElMessage.success("保存成功");
          } else {
            ElMessage.success("提交成功");
          }
          handleCancel(1);
        }
      });
    }
  });
};

async function getDetail() {
  handleApiResponse(() =>
    GetGlassesStorePurchaseOrderDetail({ id: props.detailForm.id })
  ).then((res) => {
    if (res.code == 0) {
      //   console.log(res);
      addForm.value = res.data.order || {};
      addForm.value.businessTime = addForm.value.businessTime * 1000;
      tableData.value = res.data.order.items || [];
      tableData.value.forEach((item) => {
        item.priceAtOrder = item.priceAtOrder / 100;
      });
    }
  });
}

const tableData = ref([]);

// 处理选择完后的商品数据
const product_drawer = ref(false);
const openDrawer = () => {
  product_drawer.value = true;
};
const handleChangeProductSuccess = (val) => {
  //   console.log(val);
  val.deleteId = new Date().getTime();
  val.specsDescription = val.specsDescription.join(";");
  val.priceAtOrder = val.goodsPrice ? val.goodsPrice : 0;
  val.count = 1;
  tableData.value.push(cloneDeep(val));
  product_drawer.value = false;
};

const deleteRow = (deleteId) => {
  tableData.value = tableData.value.filter(
    (item) => item.deleteId !== deleteId
  );
};

// 两个数相乘，返回一个数值
const handleMul = (num1, num2) => {
  let num = new Decimal(num1).mul(num2).toString();
  return +num;
};

const rules = ref({
  providerId: [{ required: true, message: "请选择供应商名称" }],
  businessUserId: [{ required: true, message: "请选择业务员" }],
  businessTime: [{ required: true, message: "请选择采购时间" }],
});

watchEffect(() => {
  tableData.value.forEach((item) => {
    if (!item.priceAtOrder) {
      item.priceAtOrder = 0;
    }
    if (!item.count) {
      item.count = 1;
    }
  });
});
</script>

<style scoped lang="scss">
</style>